package org.malred.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.malred.common.BaseContext;
import org.malred.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        log.info("拦截到请求: {}", req.getRequestURI());

        // 获取uri
        String requestURI = req.getRequestURI();
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                // 静态资源也放行
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };

        // 判断是否放行
        boolean check = check(urls, requestURI);

        // 不需要处理就直接放行
        if (check) {
            log.info("本次请求{}不需要处理", requestURI);
            chain.doFilter(request, response);
            return;
        }

        // 判断登录状态
        Object employee = req.getSession().getAttribute("employee");
        if (employee != null) {
            log.info("用户已登录, 用户id为: {}", employee);

            BaseContext.setCurrentId((Long) employee);
            long id = Thread.currentThread().getId();
            log.info("线程id为: {}", id);

            chain.doFilter(request, response);
            return;
        }

        Object user = req.getSession().getAttribute("user");
        if (user != null) {
            log.info("用户已登录, 用户id为: {}", user);

            BaseContext.setCurrentId((Long) user);
            long id = Thread.currentThread().getId();
            log.info("线程id为: {}", id);

            chain.doFilter(request, response);
            return;
        }

        // 没有登录就响应给前端
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 路径匹配, 检查是否放行
     *
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
